package constant_tools;

import domain.EntityPerson;
import domain.VirtualUser;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;

public class UserTools {
    public static String StringtoMD5(String psword) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(psword.getBytes());
            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String addSalt(VirtualUser virtualUser){

        BigInteger len = BigInteger.valueOf(virtualUser.getPsword().length());

        BigInteger createDateTimeBigInteger = BigInteger.valueOf(virtualUser.getCreate_date_time().getTime());

        BigInteger save = createDateTimeBigInteger.remainder(len);

        return UserTools.StringtoMD5(new StringBuffer(virtualUser.getPsword()).insert(save.intValue(),"salt").toString());

    }

    public static String Enigma(String password){

        char [] toChar = password.toCharArray();

        int []n = {4,6,10};

        int n_num = 3;

        int char_code;

        char[] out = new char[toChar.length];


        for (int i=0;i<toChar.length;i++) {
            char_code = toChar[i] - 'a';

            for (int j = 0; j < n_num; j++) {
                char_code = (char_code + n[j]) % 26;
            }

            if(char_code%2==0)
                char_code++;
            else
                char_code--;

            for(int j=n_num-1;j>=0;j--){
                char_code = char_code-n[j];
                if(char_code<0)
                    char_code+=26;
            }

            n[0]++;

            for (int j = 0; j < n_num-1; j++)
            {
                if (n[j]>=26)
                {
                    n[j + 1]++;
                    n[j] = 0;
                }
            }
            n[n_num-1] = n[n_num-1] % 26;
            out[i] = (char) (n_num+'a');



        }
        return new String(out);
    }


}
